layui.use(['layer', 'form', 'table'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;

    var realAccountId = "";

    /**
     * 集团信息--集团综合信息
     */
    var Bloc = {
        tableId: "blocTable",    //表格id
        condition: {
            accountId: ""
        }
    };

    /**
     * 从上个月开始的前6个月
     */
    function searchSixMonth(){
        var curr = new Date();
        for (var i = 0; i < 6; i ++) {
            curr.setDate(1);
            curr.setMonth(curr.getMonth() - 1);
            var yearVal = curr.getFullYear();
            var monthVal = curr.getMonth() + 1;
            if (monthVal < 10) {
                monthVal = "0" + monthVal;
            }
            var dateStr = yearVal + "" + monthVal;
            $('#dateSecond').append(new Option(dateStr, dateStr));
            $('#dateThird').append(new Option(dateStr, dateStr));
        }
    };
    searchSixMonth();

    /**
     * 从前天开始的前七天
     */
    function searchSevenDays(){
        var curr = new Date();
        curr.setDate(curr.getDate() - 1);
        for (var i = 0; i < 7; i ++) {
            curr.setDate(curr.getDate() - 1);
            var yearVal = curr.getFullYear();
            var monthVal = curr.getMonth() + 1;
            if (monthVal < 10) {
                monthVal = "0" + monthVal;
            }
            var dayVal = curr.getDate();
            if (dayVal < 10) {
                dayVal = "0" + dayVal;
            }
            var dateStr = yearVal + "" + monthVal + "" + dayVal;
            $('#dateFourth').append(new Option(dateStr, dateStr));
        }
    };
    searchSevenDays();

    /**
     * 初始化表格的列
     */
    Bloc.initColumn = function () {
        return [[
            {field: 'accountId', hide: true, title: '账号id'},
            {field: 'blocName', align: "center", title: '集团名称'},
            {field: 'ecId', align: "center", title: '集团编码'},
            {field: 'totalCards', align: "center", title: '总卡数'},
            {align: "center", toolbar: '#menuWhiteList', title: '集团短信白名单', minWidth: 200},
            {align: "center", toolbar: '#orderCharges', title: '已订购资费', minWidth: 200}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Bloc.searchBloc = function () {
        realAccountId = $("#accountId").val();
        var queryData = {};
        queryData['accountId'] = $("#accountId").val();
        searchStatusNumber();
        searchEcBill();
        searchRiskLevel();
        searchHighRisk();
        table.reload(Bloc.tableId, {
            where: queryData
        });
        searchAccount(realAccountId);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Bloc.tableId,
        toolbar: '#toolbarDemo',
        defaultToolbar: [],
        url: Feng.ctxPath + '/blocSyn/list',
        page: false,
        height: 180,
        cellMinWidth: 100,
        cols: Bloc.initColumn()
    });

    //监听头工具栏事件
    table.on('toolbar(' + Bloc.tableId + ')', function(obj){//获取选中的数据
        switch(obj.event){
            case 'search':
                Bloc.searchBloc();
                break;
        };
    });

    //工具条点击事件
    table.on('tool(' + Bloc.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'searchWhiteList') {
            Bloc.searchWhiteList(data);
        }
        else if (layEvent === 'searchOrder') {
            Bloc.searchOrder(data);
        }
    });

    /**
     * 查看集团短信白名单
     *
     * @param data 点击按钮时候的行数据
     */
    Bloc.searchWhiteList = function (data) {
        layer.open({
            type: 2,
            title: '集团短信白名单',
            area: ['850px', '550px'],
            skin: 'layui-layer-molv',
            content: Feng.ctxPath + '/blocSyn/blocSyn_whiteList/' + data.accountId,
            btn: ['关闭']
        });
    };

    /**
     * 查看已订购资费
     *
     * @param data 点击按钮时候的行数据
     */
    Bloc.searchOrder = function (data) {
        layer.open({
            type: 2,
            title: '集团已订购资费',
            area: ['950px', '650px'],
            skin: 'layui-layer-molv',
            content: Feng.ctxPath + '/blocSyn/blocSyn_orderCharges/' + data.accountId,
            btn: ['关闭']
        });
    };

    /**
     * 查询物联卡生命周期分别信息，填充echarts
     */
    function searchStatusNumber(){
        $.ajax({
            url: Feng.ctxPath + "/blocSyn/statusNumber?accountId=" + realAccountId,
            dataType: 'json',
            type: 'post',
            success: function (data) {
                var obj;
                obj = document.getElementById("firstError");
                if(data["error"] != null){
                    obj.innerHTML = data["error"];
                    $("#firstError").show();
                    $("#first").hide();
                }else {
                    $("#firstError").hide();
                    $("#first").show();
                    myChartFirst.hideLoading();    //隐藏加载动画
                    myChartFirst.setOption({
                        series: [
                            {
                                name: '状态',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '50%'],
                                selectedMode: 'single',
                                label: {
                                    formatter: '\n  {c}  {per|{d}%}  \n',
                                    fontSize: 15,
                                    backgroundColor: '#eee',
                                    borderColor: '#aaa',
                                    borderWidth: 1,
                                    borderRadius: 4,
                                    rich: {
                                        per: {
                                            color: '#eee',
                                            backgroundColor: '#334455',
                                            padding: [2, 4],
                                            borderRadius: 2
                                        }
                                    }
                                },
                                data: [
                                    {value: data["testNum"], name: '可测试'},
                                    {value: data["readyNum"], name: '待激活'},
                                    {value: data["inactNum"], name: '库存'},
                                    {value: data["actNum"], name: '已激活'},
                                    {value: data["suspendNum"], name: '已停机'},
                                    {value: data["preTerNum"], name: '预销户'}
                                ]
                            }
                        ],
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            bottom: 1,
                            left: 'center',
                            data: ['可测试', '待激活', '库存', '已激活', '已停机', '预销户']
                        }
                    });
                }
            }
        });
    };
    searchStatusNumber();

    /**
     * 查询集团月总账单，填充数据到echarts
     */
    function searchEcBill(){
        $.ajax({
            url: Feng.ctxPath + "/blocSyn/ecBill?queryDate=" + $("#dateSecond").val() + "&accountId=" + realAccountId,
            dataType: 'json',
            type: 'post',
            success: function (data) {
                var obj;
                obj = document.getElementById("secondError");
                if(data["echartsStatus"] === 1){
                    obj.innerHTML = data["error"];
                    $("#secondError").show();
                    $("#second").hide();
                }else {
                    $("#secondError").hide();
                    $("#second").show();
                    myChartSecond.hideLoading();    //隐藏加载动画
                    myChartSecond.setOption({
                        dataset: {
                            source: [
                                ['product', '费用总金额(元)', '未缴费总金额(元)'],
                                [data["queryDate"], data["invoiceAmount"], data["openAmount"]]
                            ]
                        },
                        legend: {
                            bottom: 1,
                            left: 'center',
                            data: ['费用总金额(元)', '未缴费总金额(元)']
                        },
                        tooltip: {},
                        xAxis: {type: 'category'},
                        yAxis: {},
                        series: [
                            {type: 'bar', barWidth: '25%', label: seriesLabel},
                            {type: 'bar', barWidth: '25%', label: seriesLabel}
                        ]
                    });
                }
            }
        });
    };
    searchEcBill();

    /**
     * 查询物联卡风险等级分布，填充数据到echarts
     */
    function searchRiskLevel(){
        $.ajax({
            url: Feng.ctxPath + "/blocSyn/riskLevel?queryDate=" + $("#dateThird").val() + "&accountId=" + realAccountId,
            dataType: 'json',
            type: 'post',
            success: function (data) {
                var obj;
                obj=document.getElementById("thirdError");
                if(data["error"] != null){
                    obj.innerHTML=data["error"];
                    $("#thirdError").show();
                    $("#third").hide();
                }else {
                    $("#thirdError").hide();
                    $("#third").show();
                    myChartThird.hideLoading();    //隐藏加载动画
                    myChartThird.setOption({
                        series: [
                            {
                                name: '风险等级',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '50%'],
                                selectedMode: 'single',
                                label: {
                                    formatter: '\n  {c}  {per|{d}%}  \n',
                                    fontSize: 15,
                                    backgroundColor: '#eee',
                                    borderColor: '#aaa',
                                    borderWidth: 1,
                                    borderRadius: 4,
                                    rich: {
                                        per: {
                                            color: '#eee',
                                            backgroundColor: '#334455',
                                            padding: [2, 4],
                                            borderRadius: 2
                                        }
                                    }
                                },
                                data: [
                                    {value: data["risk001"], name: 'risk001:高风险'},
                                    {value: data["risk002"], name: 'risk002:中风险'},
                                    {value: data["risk003"], name: 'risk003:低风险'},
                                    {value: data["risk004"], name: 'risk004:安全'}
                                ]
                            }
                        ],
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            bottom: 1,
                            left: 'center',
                            data: ['risk001:高风险', 'risk002:中风险', 'risk003:低风险', 'risk004:安全']
                        }
                    });
                }
            }
        });
    };
    searchRiskLevel();

    /**
     * 查询高风险物联卡类型分布，填充数据到echarts
     */
    function searchHighRisk(){
        $.ajax({
            url: Feng.ctxPath + "/blocSyn/highRisk?queryDate=" + $("#dateFourth").val() + "&accountId=" + realAccountId,
            dataType: 'json',
            type: 'post',
            success: function (data) {
                var obj;
                obj=document.getElementById("fourthError");
                if(data["error"] != null){
                    obj.innerHTML=data["error"];
                    $("#fourthError").show();
                    $("#fourth").hide();
                }else {
                    $("#fourthError").hide();
                    $("#fourth").show();
                    myChartFourth.hideLoading();    //隐藏加载动画
                    myChartFourth.setOption({
                        series: [
                            {
                                name: '高风险类型',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '50%'],
                                selectedMode: 'single',
                                label: {
                                    formatter: '\n  {c}  {per|{d}%}  \n',
                                    fontSize: 15,
                                    backgroundColor: '#eee',
                                    borderColor: '#aaa',
                                    borderWidth: 1,
                                    borderRadius: 4,
                                    rich: {
                                        per: {
                                            color: '#eee',
                                            backgroundColor: '#334455',
                                            padding: [2, 4],
                                            borderRadius: 2
                                        }
                                    }
                                },
                                data: [
                                    {value: data["risk001001"], name: 'risk001001:开通非定向语音且在敏感区域漫游使用'},
                                    {value: data["risk001002"], name: 'risk001002:开通非定向语音且在手机终端使用'},
                                    {value: data["risk001003"], name: 'risk001003:手机类终端上使用过且发生机卡分离'}
                                ]
                            }
                        ],
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b} : {c} ({d}%)'
                        },
                        legend: {
                            bottom: 1,
                            left: 'center',
                            // orient: 'vertical',
                            data: ['risk001001:开通非定向语音且在敏感区域漫游使用',
                                'risk001002:开通非定向语音且在手机终端使用',
                                'risk001003:手机类终端上使用过且发生机卡分离']
                        }
                    });
                }
            }
        });
    };
    searchHighRisk();

    /**
     * 监听集团总账单月份变换时调用接口
     */
    $("#dateSecond").change(function(){
        searchEcBill();
    });

    /**
     * 监听物联卡风险等级分布月份变换时调用接口
     */
    $("#dateThird").change(function(){
        searchRiskLevel();
    });

    /**
     * 监听高风险物联卡类型分布时间变换时调用接口
     */
    $("#dateFourth").change(function(){
        searchHighRisk();
    });

    // 基于准备好的dom，初始化echarts实例
    var myChartFirst = echarts.init(document.getElementById('first'), myEchartsTheme);
    var myChartSecond = echarts.init(document.getElementById('second'), myEchartsTheme);
    var myChartThird = echarts.init(document.getElementById('third'), myEchartsTheme);
    var myChartFourth = echarts.init(document.getElementById('fourth'), myEchartsTheme);

    var seriesLabel = {
        normal: {
            show: true,
            textBorderWidth: 2,
            position:'top'
        }
    }

    /**
     * 查询所有的账号信息，填充select标签
     */
    function searchAccount(accountId) {
        $('#accountId').html('');
        $("#accountId").append('<option value="" >请选择</option>');
        $.ajax({
            type: 'get',
            url: Feng.ctxPath + "/account/allSelectAccounts",
            async: false,
            success: function (data) {
                for (var i = 0; i < data.data.length; i++) {
                    var name = data.data[i].accountName;
                    var code = data.data[i].accountId;
                    if (accountId == code) {
                        $("#accountId").append('<option value="' + code + '" selected>' + name + '</option>');
                    } else {
                        $("#accountId").append('<option value="' + code + '">' + name + '</option>');
                    }
                }
                form.render('select');
            }
        });
    }
    searchAccount();
});